package com.lm.redis.example;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.Set;

public class RedisDelayedQueueExample {
    private static final String QUEUE_KEY = "delayed_queue";
    private Jedis jedis;

    public RedisDelayedQueueExample() {
        jedis = new Jedis("192.168.1.181",6379);
        jedis.auth("123456?");
    }

    public void push(String message, long delay) {
        long score = System.currentTimeMillis() + delay;
        jedis.zadd(QUEUE_KEY, score, message);
    }

    public String pop() {
        Set<Tuple> messages = jedis.zrangeByScoreWithScores(QUEUE_KEY, 0, System.currentTimeMillis(), 0, 1);
        if (messages.isEmpty()) {
            return null;
        }

        Tuple message = messages.iterator().next();
        String messageValue = message.getElement();
        jedis.zrem(QUEUE_KEY, messageValue);
        return messageValue;
    }

    public static void main(String[] args) throws InterruptedException {
        RedisDelayedQueueExample example = new RedisDelayedQueueExample();

        // 将消息推送到延时队列
        example.push("message1", 5000);
        example.push("message2", 10000);

        // 从延时队列中弹出消息
        System.out.println(example.pop()); // null

        // 等待5秒钟
        Thread.sleep(5000);

        // 从延时队列中弹出消息
        System.out.println(example.pop()); // message1

        // 等待5秒钟
        Thread.sleep(5000);

        // 从延时队列中弹出消息
        System.out.println(example.pop()); // message2
    }
}
